package com.dogkr.server.web.guest;

import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.dogkr.common.Constants;
import com.dogkr.common.ServerAction;
import com.dogkr.server.entity.User;
import com.dogkr.server.service.UserService;
import com.sean.common.action.BaseAction;
import com.sean.common.utils.StringUtils;


// 设置Struts2注解
@ParentPackage(value = "project-default")
@Namespace(value = "/login")
@ResultPath("/WEB-INF/jsps")
// 页面文件空间
@Results({
	@Result(name = "index", location = "index.jsp")
})
public class LoginAction extends ServerAction {
	
	private static final long serialVersionUID = 1L;
	
	private String redirectURL;
	
	@Autowired
	private UserService userService;
	
	@Action(value = "login")
	public void login() {
		String username = this.get("username");
		String password = this.get("password");
		if(StringUtils.isNotBlank(username, password)) {
			User user = userService.selectByLoginName(username);
			if(user == null) {
				res = this.getErrRes("用户不存在.");
			} else if(!user.getLoginPassword().equals(DigestUtils.md5Hex(password))) {
				res = this.getErrRes("密码错误.");
			} else {
				User updateUser = new User();
				updateUser.setId(user.getId());
				updateUser.setLastLogindate(new Date());
				userService.updateByPrimaryKeySelective(updateUser);
				getSessiont().setAttribute(Constants.LOGIN_USER_KEY, user);
			}
		} else {
			res = this.getErrRes("用户或密码未填写");
		}
		outJson(res);
	}
	
	@Action(value = "logout")
	public void logout() {
		try {
			this.getSessiont().removeAttribute(Constants.LOGIN_USER_KEY);
		} catch (Exception e) { 
			log.warn("logout error:user not login.");
		}
	}
	
	@Action(value = "index")
	public String index() {
		return "index";
	}
	
	@Action(value = "issign")
	public void issign() {
		User user = this.getLoginUser();
		if(user != null) {
			res.put("user", user);
			outJson(res);
		} else {
			outJson(this.getErrRes(""));
		}
	}

	public String getRedirectURL() {
		return redirectURL;
	}

	public void setRedirectURL(String redirectURL) {
		this.redirectURL = redirectURL;
	}
}
